package heman.server.controllers;


import java.util.ArrayList;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.server.interfaces.IProcessServerMessage;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Chat controller handles CHAT messages.
 * 
 * <xs:element name="chat">
 * <xs:complexType>
 *  <xs:sequence>
 *    <xs:element ref="player-id" minOccurs='0' maxOccurs='unbounded'/>
 *    <xs:element ref="text"/>
 *  </xs:sequence>
 * </xs:complexType>
 * </xs:element>
 * 
 * @author WenlongLiu
 *
 */
public class ChatController implements IProcessServerMessage {

	public boolean process(Communicator com, Message m) {
		String originator = m.getOriginator();
		//Node text = m.contentsChild();
        //String s = text.getTextContent();
        
        // get all players to which this chat is intended. If no 
        // players then we do a broadcast-minus-self
        ArrayList<String> targets = new ArrayList<String>();
        
        // traverse the XML DOM to retrieve the child PLAYER 
        // nodes and from them retrieve PLAYER attributes.
        Node root = m.contents();
        NodeList children = root.getChildNodes();
        String textString=null;
        for (int i = 0; i < children.getLength(); i++) {
        	Node child = children.item(i);
        	
        	// if a PLAYER-ID node, then add to our targets set
        	if (child.getNodeName().equals("player-id")) {
        		// get the "player" attribute from that node.
        		NamedNodeMap map = child.getAttributes();
        		Node pname = map.getNamedItem("player");
        		targets.add(pname.getNodeValue());
        	}else if (child.getNodeName().equals("text")){
        		textString=child.getTextContent();
        	}
        }
        
        // produce successful request. note that client is responsible 
        // now for tagging from.
        StringBuilder sb = new StringBuilder(Message.responseHeader(true));
        sb.append("<output from='" + originator);
        
        if (targets.isEmpty())
        	sb.append("' public=\"true\"><text>");
        else 
        	sb.append("' public=\"false\"><text>");
        sb.append(textString);
        
        sb.append("</text></output></response>");
        Document d = Message.construct(sb.toString());
        
        Message r = new Message (d);
        r.setOriginator(originator);
        if (targets.isEmpty()) {
	        // send to all clients EXCEPT self.
	        r.setBroadcast();
	        return com.distribute(r);
        } else {
        	return com.distribute(targets.iterator(), r);
        }
	}

}
